//
//  MMContrastAuthorVC.swift
//  ChanMaMa
//
//  Created by 戴泉明 on 2021/4/21.
//  Copyright © 2021 蝉妈妈-戴泉明. All rights reserved.
//  对比


import UIKit
import SnapKit


//声明代理
protocol ContrastCellHeightDelegate: class {
    func e_tableViewCellHeight(_ indexPath: IndexPath) -> CGFloat
    func e_tableViewCellColor(_ indexPath: IndexPath) -> UIColor
}

class MMContrastAuthorVC: UIViewController {
    
    //数据源
    private var isDing: Bool = false//是否有钉住
    private var isDifference: Bool = false//是否只显示不同
    private var orientation:UIDeviceOrientation = .faceUp
    private var dataArr: [ContrastModel] = []
    private var sourceArr: [ContrastModel] = []
    var cellHeightDictionary:[IndexPath: CGFloat] = [:]//高度缓存
    var cellValueDictionary:[IndexPath: String] = [:]//每一行最开始的value
    var cellOriengeColorDictionary:[IndexPath: Bool] = [:]//每一行是否要显示橘色

    //UI
    private var configView: ContrastConfigView = {
        let view = ContrastConfigView(frame: CGRect.zero)
        return view
    }()
    private var compareView: ContrastCompareView = {
        let view = ContrastCompareView(frame: CGRect.zero)
        return view
    }()
    private var dingView: ContrastDingView = {
        let view = ContrastDingView(frame: CGRect.zero)
        return view
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged(notification:)), name: UIDevice.orientationDidChangeNotification, object: nil)
        setupUI()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension MMContrastAuthorVC {
    private func setupUI() {
        self.navigationController?.navigationBar.isHidden = true
        navigationItem.title = "对比"
        view.addSubview(dingView)
        view.addSubview(compareView)
        view.addSubview(configView)
        //代理托管
        dingView.delegate = self
        compareView.delegate = self
        configView.delegate = self
        dingView.cellHeightDelegate = self
        compareView.cellHeightDelegate = self
        configView.cellHeightDelegate = self
        
        NotificationCenter.default.addObserver(self, selector: #selector(cancleDingContrastAction), name: NSNotification.Name(rawValue:"cancleDingContrastNotification"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(deleteContrastAction), name: NSNotification.Name(rawValue:"deleteContrastNotification"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(dingContrastAction), name: NSNotification.Name(rawValue:"dingContrastNotification"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(addContrastAction), name: NSNotification.Name(rawValue:"addContrastNotification"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(showDifferenceContrast), name: NSNotification.Name(rawValue:"showDifferenceContrastNotification"), object: nil)

        
        //设置约束和手势 最后触发刷新
        configUI()
        
        //模拟请求
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.loadData()
        }
        
    }
    
    //取消钉住
    @objc func cancleDingContrastAction() {
        self.isDing = false
        self.reloadUI()
        self.loadData()
    }
    //删除某个对比
    @objc func deleteContrastAction() {
        
    }
    //钉住对比
    @objc func dingContrastAction() {
        self.isDing = true
        self.reloadUI()
        self.loadData()
    }
    //添加新对比
    @objc func addContrastAction() {
        
    }
    
    //是否显示相同
    @objc func showDifferenceContrast(notification: Notification) {
        isDifference = (notification.userInfo?["show"] ?? false) as! Bool
        //通过触发设置数据源  触发刷新 将高度设为0即可达到隐藏的效果
        configView.setDatas(datas: dataArr)
        compareView.setDatas(datas: sourceArr)
        dingView.setDatas(datas: sourceArr)
    }
    
    func configUI() {
        configView.snp.makeConstraints { (make) in
            make.left.equalTo(self.view.snp.left)
            make.bottom.equalTo(self.view.snp.bottom)
            make.top.equalTo(0).offset(naviBarHeight)
            make.right.equalTo(self.view.snp.right)
        }
        compareView.snp.makeConstraints { (make) in
            make.left.equalTo(self.view.snp.left).offset(CONTRAST_CONFIG_WIDTH)
            make.bottom.equalTo(self.view.snp.bottom)
            make.top.equalTo(0).offset(naviBarHeight)
            make.right.equalTo(self.view.snp.right)
        }
        dingView.isHidden = !isDing
        dingView.snp.makeConstraints { (make) in
            make.left.equalTo(self.view.snp.left).offset(CONTRAST_CONFIG_WIDTH)
            make.bottom.equalTo(self.view.snp.bottom)
            make.top.equalTo(0).offset(naviBarHeight)
            make.right.equalTo(self.view.snp.right)
        }
        
        //约束完一定要重置一下 congifview的path
        let path = UIBezierPath.init(rect: CGRect(x: 0, y: 0, width: CONTRAST_CONFIG_WIDTH, height: screenHeight-Main_Top))
        configView.path = path
    }
    
    //更改数据源 刷新UI
    func reloadUI() {
        configView.snp.remakeConstraints { (make) in
            make.left.equalTo(self.view.snp.left)
            make.bottom.equalTo(self.view.snp.bottom)
            make.top.equalTo(0).offset(naviBarHeight)
            make.right.equalTo(self.view.snp.right)
        }
        compareView.snp.remakeConstraints { (make) in
            make.left.equalTo(self.view.snp.left).offset(isDing ? (CONTRAST_CONFIG_WIDTH+CONTRAST_ITEM_WIDTH) : CONTRAST_CONFIG_WIDTH)
            make.bottom.equalTo(self.view.snp.bottom)
            make.top.equalTo(0).offset(naviBarHeight)
            make.right.equalTo(self.view.snp.right)
        }
        dingView.isHidden = !isDing
        dingView.snp.remakeConstraints { (make) in
            make.left.equalTo(self.view.snp.left).offset(CONTRAST_CONFIG_WIDTH)
            make.bottom.equalTo(self.view.snp.bottom)
            make.top.equalTo(0).offset(naviBarHeight)
            make.right.equalTo(self.view.snp.right)
        }
        
        //约束完一定要重置一下 congifview的path
        let path = UIBezierPath.init(rect: CGRect(x: 0, y: 0, width: CONTRAST_CONFIG_WIDTH, height: screenHeight-Main_Top))
        configView.path = path
    }
    
    func loadData() {
        let jsonData = NSData(contentsOfFile: Bundle.main.path(forResource: "comparedata", ofType: "json") ?? "") as Data?
        var dict: [String : Any]? = nil
        do {
            if let jsonData = jsonData {
                dict = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String : Any]
            }
            //得到数组
            dataArr = ContrastBaseModel.deserialize(from: dict)?.data ?? []
            sourceArr = ContrastBaseModel.deserialize(from: dict)?.data ?? []
            
            
            //应为个数不够全屏  旋转会有问题。 填入空的以填满
//            for (i,_) in sourceArr.enumerated().reversed() {
//                if i != 1 {
//                    sourceArr.removeLast()
//                }
//            }

//            if orientation == .portrait || orientation == .portraitUpsideDown {
//                //增加一个添加的
                let addModel = ContrastModel()
                sourceArr.append(addModel)
//            } else {
//                //增加一个添加的
//                let addModel = ContrastModel()
//                let addModel1 = ContrastModel()
//                let addModel2 = ContrastModel()
//                let addModel3 = ContrastModel()
//                let addModel4 = ContrastModel()
//                let addModel5 = ContrastModel()
//                let addModel6 = ContrastModel()
//
//                sourceArr.append(addModel)
//                sourceArr.append(addModel1)
//                sourceArr.append(addModel2)
//                sourceArr.append(addModel3)
//                sourceArr.append(addModel4)
//                sourceArr.append(addModel5)
//                sourceArr.append(addModel6)
//            }

            
            //对比 获取高度  可以固定高度的话 两个for循环可以删除
            for (i,groupParamsItem) in dataArr[0].groupParamsViewModelList.enumerated() {
                for (j,paramListItem) in groupParamsItem.paramList.enumerated() {
                    let paramName = paramListItem.paramName
                    let height = self.getLabHeigh(labelStr: paramName, width: CONTRAST_CONFIG_WIDTH)
                    cellHeightDictionary[IndexPath.init(row: j, section: i)] = height + 28
                    cellValueDictionary[IndexPath.init(row: j, section: i)] = paramListItem.paramValue
                    cellOriengeColorDictionary[IndexPath.init(row: j, section: i)] = false
                }
            }
            for (_,model) in sourceArr.enumerated() {
                for (i,groupParamsItem) in model.groupParamsViewModelList.enumerated() {
                    for (j,paramListItem) in groupParamsItem.paramList.enumerated() {
                        let paramName = paramListItem.paramValue
                        let height = self.getLabHeigh(labelStr: paramName, width: CONTRAST_CONFIG_WIDTH)
                        if (height + 28) > (cellHeightDictionary[IndexPath.init(row: j, section: i)] ?? 0) {
                            cellHeightDictionary[IndexPath.init(row: j, section: i)] = height + 28
                        }
                        //有不相等的 标记为橘色
                        if paramName != (cellValueDictionary[IndexPath.init(row: j, section: i)] ?? "") {
                            cellOriengeColorDictionary[IndexPath.init(row: j, section: i)] = true
                        }
                    }
                }
            }
            
            configView.setDatas(datas: dataArr)
            compareView.setDatas(datas: sourceArr)
            dingView.setDatas(datas: sourceArr)
            
        } catch {
            print("数据处理错误！！！！")
        }
    }
    
     func getLabHeigh(labelStr:String, width:CGFloat) -> CGFloat {
        let attStr = NSMutableAttributedString.init(string: "\(labelStr)")
        let range1 = NSRange(location: 0, length: labelStr.count-1)
        attStr.addAttributes([.foregroundColor:UIColor.init(ts_hexString: "#8F959E"), .font:UIFont.systemFont(ofSize: 12)], range: range1)
        let size = attStr.boundingRect(with: CGSize(width: width, height: 900), options: .usesLineFragmentOrigin, context: nil)
        return size.height
      }
}

extension MMContrastAuthorVC: ContrastScrollDelegate, ContrastCellHeightDelegate {
    func e_scrollViewDidScroll(_ scrollView: UIScrollView?) {
        guard scrollView != nil else {
            return
        }
        let offset = scrollView!.contentOffset
        if scrollView == configView.tableView {
            compareView.tableView.contentOffset = offset
            dingView.tableView.contentOffset = offset
        } else if scrollView == compareView.tableView {
            configView.tableView.contentOffset = offset
            dingView.tableView.contentOffset = offset
        } else if scrollView == dingView.tableView {
            configView.tableView.contentOffset = offset
            compareView.tableView.contentOffset = offset
        }
    }
    
    
    func e_tableViewCellHeight(_ indexPath: IndexPath) -> CGFloat {
        if isDifference && !(cellOriengeColorDictionary[indexPath] ?? false) {
            return 0//会卡顿
        }
        return cellHeightDictionary[indexPath] ?? 100
    }
    func e_tableViewCellColor(_ indexPath: IndexPath) -> UIColor {
        return cellOriengeColorDictionary[indexPath] ?? false ? UIColor.init(ts_hexString: "#FF7752",alpha: 0.08) :  UIColor.white
    }
}


extension MMContrastAuthorVC {
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        print("选转")
        
//        loadData()

    }
    
    override func viewLayoutMarginsDidChange() {
        let path = UIBezierPath.init(rect: CGRect(x: 0, y: 0, width: CONTRAST_CONFIG_WIDTH, height: screenHeight-Main_Top))
        configView.path = path
        
        print("\(screenWidth)   \(screenHeight)")
    }
    
    @objc func orientationChanged(notification: Notification) {
//        let o = UIDevice.current.orientation
//        orientation = o
//        switch o {
//        case .portrait, .portraitUpsideDown:
//            reloadUI()
//            loadData()
//        case .landscapeLeft, .landscapeRight:
//            reloadUI()
//            loadData()
//        default:
//            break
//        }
    }
    
}
